package cn.broadmax.boot.modules.sys.bean;

import cn.broadmax.boot.modules.sys.entity.SysResource;
import jexx.util.CollectionUtil;
import jexx.util.ObjectUtil;
import jexx.util.StringUtil;
import jexx.util.TreeUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@Data
@EqualsAndHashCode(callSuper = true)
public class SysResourceTree extends SysResource implements Comparable<SysResourceTree> {

    private List<SysResourceTree> children;

    public static List<SysResourceTree> toResourceTree(List<SysResource> list){
        List<SysResourceTree> resourceTreeList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            for(SysResource resource : list){
                SysResourceTree resourceTree = new SysResourceTree();
                BeanUtils.copyProperties(resource, resourceTree);
                resourceTreeList.add(resourceTree);
            }
        }
        return resourceTreeList;
    }

    public static List<SysResourceTree> buildResourceTree(List<SysResource> list){
        List<SysResourceTree> resourceTreeList = toResourceTree(list);
        return TreeUtil.buildTree(resourceTreeList, new TreeUtil.TreeMapper<SysResourceTree, String>() {
            @Override
            public String getId(SysResourceTree sysResource) {
                return sysResource.getId();
            }

            @Override
            public String getParentId(SysResourceTree sysResource) {
                return sysResource.getParentId();
            }

            @Override
            public void addChild(SysResourceTree parent, SysResourceTree child) {
                List<SysResourceTree> children = parent.getChildren();
                if (children == null) {
                    children = new ArrayList<>();
                    parent.setChildren(children);
                }
                children.add(child);
            }

            @Override
            public boolean isRoot(SysResourceTree sysResource) {
                return StringUtil.isEmpty(sysResource.getParentId());
            }
        });
    }


    @Override
    public int compareTo(SysResourceTree o) {
        int s1 = ObjectUtil.notNullOrDefault(this.getSort(), 0);
        int s2 = ObjectUtil.notNullOrDefault(o.getSort(), 0);
        return s1 - s2;
    }
}
